<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="监控类型" prop="monitoringType">
        <el-select
          v-model="queryParams.monitoringType"
          placeholder="请选择监控类型"
          clearable
          class="!w-240px"
        >
          <el-option label="人员监控" value="personnel" />
          <el-option label="设备监控" value="equipment" />
          <el-option label="环境监控" value="environment" />
          <el-option label="流程监控" value="process" />
          <el-option label="质量监控" value="quality" />
        </el-select>
      </el-form-item>
      <el-form-item label="监控状态" prop="monitoringStatus">
        <el-select
          v-model="queryParams.monitoringStatus"
          placeholder="请选择监控状态"
          clearable
          class="!w-240px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="异常" :value="1" />
          <el-option label="警告" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="监控时间" prop="monitoringTime">
        <el-date-picker
          v-model="queryParams.monitoringTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:monitoring:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="openRealTimeMonitoring"
          v-hasPermi="['eval:monitoring:real-time']"
        >
          <Icon icon="ep:monitor" class="mr-5px" /> 实时监控
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:monitoring:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 监控统计卡片 -->
  <el-row :gutter="20" class="mb-4">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ statistics.totalCount || 0 }}</div>
            <div class="text-gray-500">总监控数</div>
          </div>
          <Icon icon="ep:monitor" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ statistics.normalCount || 0 }}</div>
            <div class="text-gray-500">正常</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-orange-600">{{ statistics.warningCount || 0 }}</div>
            <div class="text-gray-500">警告</div>
          </div>
          <Icon icon="ep:warning" class="text-4xl text-orange-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ statistics.exceptionCount || 0 }}</div>
            <div class="text-gray-500">异常</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 监控图表 -->
  <ContentWrap class="mb-4">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-lg font-semibold">监控趋势</h3>
      <el-radio-group v-model="chartTimeRange" @change="loadChartData">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
      </el-radio-group>
    </div>
    <div ref="chartRef" style="height: 300px;"></div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="评价计划" align="center" prop="planName" width="200" />
      <el-table-column label="监控类型" align="center" prop="monitoringType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_MONITORING_TYPE" :value="scope.row.monitoringType" />
        </template>
      </el-table-column>
      <el-table-column label="监控内容" align="center" prop="monitoringContent" width="200" />
      <el-table-column label="监控时间" align="center" prop="monitoringTime" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.monitoringTime) }}
        </template>
      </el-table-column>
      <el-table-column label="监控结果" align="center" prop="monitoringResult" width="200" />
      <el-table-column label="监控状态" align="center" prop="monitoringStatus" width="100">
        <template #default="scope">
          <el-tag :type="getMonitoringStatusTagType(scope.row.monitoringStatus)">
            {{ getMonitoringStatusText(scope.row.monitoringStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="监控说明" align="center" prop="monitoringComments" width="200" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:monitoring:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:monitoring:update']"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="handle" v-if="scope.row.monitoringStatus === 1">
                  处理异常
                </el-dropdown-item>
                <el-dropdown-item command="confirm">
                  确认
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MonitoringForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <MonitoringDetail ref="detailRef" />
  
  <!-- 实时监控弹窗 -->
  <RealTimeMonitoring ref="realTimeRef" />
  
  <!-- 异常处理弹窗 -->
  <ExceptionHandle ref="exceptionHandleRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter, formatDateTime } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalMonitoringDataVO, 
  EvalMonitoringDataPageReqVO, 
  getMonitoringDataPage, 
  deleteMonitoringData, 
  exportMonitoringData,
  getMonitoringStatistics,
  handleMonitoringException,
  confirmMonitoringData
} from '@/api/eval/monitoring'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import MonitoringForm from './MonitoringForm.vue'
import MonitoringDetail from './MonitoringDetail.vue'
import RealTimeMonitoring from './RealTimeMonitoring.vue'
import ExceptionHandle from './ExceptionHandle.vue'

/** 实施监控 列表 */
defineOptions({ name: 'EvalMonitoring' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalMonitoringDataVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const statistics = ref<any>({}) // 统计数据
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const chartRef = ref() // 图表引用
const chartTimeRange = ref('today') // 图表时间范围
const queryParams = reactive<EvalMonitoringDataPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  monitoringType: undefined,
  monitoringStatus: undefined,
  monitoringTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getMonitoringDataPage(queryParams)
    list.value = data.list
    total.value = data.total
    
    // 加载统计数据
    await loadStatistics()
  } finally {
    loading.value = false
  }
}

/** 加载统计数据 */
const loadStatistics = async () => {
  try {
    statistics.value = await getMonitoringStatistics()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 加载图表数据 */
const loadChartData = async () => {
  // 实现图表数据加载逻辑
  console.log('加载图表数据:', chartTimeRange.value)
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 实时监控操作 */
const realTimeRef = ref()
const openRealTimeMonitoring = () => {
  realTimeRef.value.open()
}

/** 异常处理操作 */
const exceptionHandleRef = ref()
const openExceptionHandle = (id: number) => {
  exceptionHandleRef.value.open(id)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalMonitoringDataVO) => {
  switch (command) {
    case 'handle':
      openExceptionHandle(row.id!)
      break
    case 'confirm':
      await handleConfirm(row.id!)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 确认监控数据 */
const handleConfirm = async (id: number) => {
  try {
    await confirmMonitoringData(id)
    message.success('确认成功')
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteMonitoringData(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportMonitoringData(queryParams)
    download.excel(data, '实施监控.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取监控状态标签类型 */
const getMonitoringStatusTagType = (status: number) => {
  const typeMap = { 0: 'success', 1: 'danger', 2: 'warning' }
  return typeMap[status] || ''
}

/** 获取监控状态文本 */
const getMonitoringStatusText = (status: number) => {
  const textMap = { 0: '正常', 1: '异常', 2: '警告' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取进行中的计划
    planList.value = await getPlanListByStatus(4) // 进行中
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
  loadChartData()
})
</script>
